#Author: Tanyong
# *-* coding:utf8 *-*
# @time       : 2018/7/18 16:14
# @Author     : Tanyong
# @Site       : 
# @File       : views.py
# @Software   : PyCharm
from flask import flash
from flask import redirect
from flask import render_template
from flask import url_for
from wtforms import StringField
from wtforms.validators import DataRequired

from info import db
from info.models import  Focus, Info
from . import center_blu


@center_blu.route('/center')
def center():
    datainfo = Focus.query.all()
    return render_template("home/center.html", datainfo=datainfo)

@center_blu.route('/center/cancel_focus/<id>')
def cancel_focus(id):
    """取消关注"""
    # 1, 先查询关注列表里 是否有这只股票
    stock = Focus.query.filter(Focus.id==id).first()
    if not stock:
        # 没有这只股票, 闪现无法取消关注
        flash("都没有关注过此股票, 你在开玩笑?")
    else:
        # 有查询到, 则再去从类表中删除
        try:
            db.session.delete(stock)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(e)
            flash("取消关注失败!")
    # 删除完成之后, 重新刷新个人中心
    return redirect(url_for("center.center"))


@center_blu.route('/center/update_page/<id>', methods=['GET', 'POST'])
def update_page(id):
    """修改备注信息"""
    # 1, 先查询关注列表里 是否有这只股票
    stock = Focus.query.filter(Focus.id==id).first()
    from .forms import UpdateForm
    class Update_page_Form(UpdateForm):
        code = StringField("股票代码", validators=[DataRequired("请输入股票代码")], default=stock.infos.code)
        note_info = StringField("备注信息", validators=[DataRequired("请输入备注信息")], default=stock.note_info)
    form = Update_page_Form()

    if not stock:
        # 没有这只股票, 闪现无法取消关注
        flash("都没有关注过此股票, 你在开玩笑?")
    else:
        if form.validate_on_submit():
            data = form.data
            stock.note_info = data['note_info']
            try:
                db.session.commit()
            except Exception as e:
                db.session.rollback()
                print(e)
                flash("修改信息失败!")
            return redirect(url_for("center.center"))

    return render_template("home/update.html", form=form)
